import LoginWrapper from '@/components/login-wrapper';
import Layout from '@/layouts/basic-layout';
import { isInIcestark } from '@ice/stark-app';
import { config, IRouterConfig, lazy } from 'ice';
import { RouteComponentProps } from 'react-router';
import { MODULE_NAME } from '../build.config';
import { APP_NAME } from './constants';

const Welcome = lazy(() => import('@/pages/welcome'));
const Login = lazy(() => import('@/pages/login'));
const ForgetPwd = lazy(() => import('@/pages/forget-pwd'));
const NotFound = lazy(() => import('@/pages/not-found'));
const NoSystemAuth = lazy(() => import('@/pages/no-system-auth'));

// 考核跟踪
const SalesVolume = lazy(() => import('@/pages/examine-tracking/sales-volume'));
const Examine = lazy(() => import('@/pages/examine-tracking/examine'));
const TestComponents = lazy(() => import('@/pages/examine-tracking/testComponents'));
const TestTable = lazy(() => import('@/pages/examine-tracking/testTable'));

const routerConfig: IRouterConfig[] = [
  createRouterConfig('/login', Login, '登录', false),
  createRouterConfig('/forget-pwd', ForgetPwd, '忘记密码', false),
  createRouterConfig('/no-auth', NoSystemAuth, '暂无权限', false),
  {
    path: '/',
    component: Layout,
    wrappers: [LoginWrapper],
    children: [
      createRouterConfig('/', Welcome, '首页', false),
      createRouterConfig('/examine-tracking/sales-volume', SalesVolume, '销量跟踪'),
      createRouterConfig('/examine-tracking/examine', Examine, '考核跟踪'),
      createRouterConfig('/examine-tracking/testComponents', TestComponents, '测试组件（勿删）'),
      createRouterConfig('/examine-tracking/testTable', TestTable, '测试表格'),
      {
        component: NotFound,
      },
    ],
  },
];

function createRouterConfig(
  path: string,
  component: React.ComponentType<RouteComponentProps<any>> | React.ComponentType<any>,
  title?: string,
  auth = true,
  pageConfig?: any,
): IRouterConfig {
  const _pageConfig = {
    title: `${title} - ${APP_NAME}`,
    ...pageConfig,
  };
  // TODO: 本地开发环境默认展示所有 menu
  if (config.env !== 'local') {
    if (auth) {
      if (isInIcestark()) {
        // 1. 子工程运行在主工程中时
        _pageConfig.auth = [`/${MODULE_NAME}${path}`];
      } else {
        // 2. 子工程独立运行时
        _pageConfig.auth = [path];
      }
    }
  }
  return {
    path,
    exact: true,
    component,
    pageConfig: _pageConfig,
  };
}

export default routerConfig;
